<template>
  <View>
    <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :center="true" name="3" multiple
              :maxCount="1" width="250" height="150" useBeforeRead="true">
      <image :src="iconData" mode="widthFix"></image>
    </u-upload>
    <u-toast ref="uToast"></u-toast>
  </View>
</template>

<script>
import {
  request,
} from '@/utils/http.js';
export default {
  name: "index",
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    uploadUrl: {
      type: String,
      default: "/user/health/base64image/upload"
    },
    uploadData: {
      type: Object,
      default() {
        return {}
      }
    },
    iconData: {
      type: String,
      default:  require('@/static/img/health-default.png')
    }
  },
  data() {
    return {
      fileList: [],
    }
  },
  methods: {
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
          filePath: url,
          encoding: 'base64',
          success: (data) => {
            let str = data.data;
            resolve(str)
          },
          fail: (err) => {
            uni.showToast({
              title: JSON.stringify(err),
              duration: 200000
            });
          }
        });
      })
    },


    uploadFn(str) {
      return new Promise((resolve, reject) => {
        request(this.uploadUrl, Object.assign({}, {
          "user_id": uni.getStorageSync('user_id'),
          "image_base64": str,
          "image_ext": 'jpeg'
        }, this.uploadData)).then(res => {
          this.$refs.uToast.show({
            message: '上传成功！'
          })
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })

    },

    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this.fileList.length
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        try{
          let data = await this.uploadFn(result)
          let item = this.fileList[fileListLen]
          this.fileList.splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: data?.datas?.url
          }))
          fileListLen++
        }
        catch(err) {
          this.$refs.uToast.show({
            message: err
          })
          this.fileList.splice(i, 1)
        }

      }
      console.log(this.fileList)
      this.$emit('change', this.fileList)
    },


    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1)
      this.$emit('change', this.fileList)
    },
  },
  watch: {
    value: {
      handler(val) {
        if(Array.isArray(val)) {
          this.fileList = [...val]
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped>

</style>